﻿using PokemonTools.Tools;
using SmallTool.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmallTool.BaseFile
{
    public class BaseCS
    {
        private BaseCS() { }
        public static readonly BaseCS instance = new BaseCS();
        public List<DataBaseConnectModel> connectList = new List<DataBaseConnectModel>();
        // 库名集合
        public List<string> dtSource = new List<string>();
        // SQL缓存
        private List<SelectSQLModel> sqlList = new List<SelectSQLModel>();
        // 生成文件保存地址
        private string createFileSavePath = string.Empty;
        // 对比软件路径
        private string bcSoftPath = string.Empty;

        /// <summary>
        /// 初始化相关数据
        /// </summary>
        public void Init()
        {
            string settingPath = string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"setting\database.txt");
            string sqlPath = string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"setting\SelectSQL.txt");
            string savePath = string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"setting\savePath.txt");
            if (!File.Exists(settingPath))
            {
                MessageBox.Show("配置文件不存在,请先配置");
                return;
            }
            using (StreamReader sr = new StreamReader(settingPath, Encoding.Default))
            {
                string line = string.Empty;
                connectList.Clear();
                while (!string.IsNullOrWhiteSpace(line = sr.ReadLine()))
                {
                    string[] arr = line.Split('|');
                    if (arr.Length == 5)
                    {
                        connectList.Add(new DataBaseConnectModel(Convert.ToInt32(arr[0]), Convert.ToBoolean(arr[1]), Convert.ToString(arr[2]), Convert.ToString(arr[3]), Convert.ToString(arr[4])));
                    }
                }
            }
            if (connectList.Count > 0 && connectList.Exists(o => o.IsOpen))
            {
                DataBaseConnectModel dcm = connectList.Find(o => o.IsOpen);
                if (dcm != null)
                {
                    string conStr = string.Format("Server={0};Database=mysql;Uid={1};Pwd={2};", dcm.IP, dcm.LoginName, dcm.PassWord);

                    string sql = "SELECT `SCHEMA_NAME` FROM `information_schema`.`SCHEMATA`";
                    try
                    {
                        using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(conStr, sql))
                        {
                            dtSource.Clear();
                            while (sdr.Read())
                            {
                                dtSource.Add(Convert.ToString(sdr["SCHEMA_NAME"]));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }

            using (StreamReader sr = new StreamReader(sqlPath, Encoding.Default))
            {
                string _strSql = string.Empty;
                sqlList.Clear();
                while (!string.IsNullOrWhiteSpace(_strSql = sr.ReadLine()))
                {
                    string[] arr = _strSql.Split('|');
                    if (arr.Length == 3)
                    {
                        sqlList.Add(new SelectSQLModel(arr[0].ToString(), arr[1].ToString(), arr[2].ToString()));
                    }
                    else if (arr.Length == 2)
                    {
                        sqlList.Add(new SelectSQLModel(arr[0].ToString(), arr[1].ToString()));
                    }
                }
            }

            using (StreamReader sr = new StreamReader(savePath, Encoding.Default))
            {
                string _path = string.Empty;
                while (!string.IsNullOrWhiteSpace(_path = sr.ReadLine()))
                {
                    string[] arr = _path.Split('|');
                    if (arr[0].Equals("1"))
                    {
                        createFileSavePath = arr[1].ToString();
                    }
                    else if (arr[0].Equals("2"))
                    {
                        bcSoftPath = arr[1].ToString();
                    }
                }


            }
        }

        /// <summary>
        /// TXT文件写入
        /// </summary>
        public void WriteTxt(string fileName)
        {
            string settingPath = string.Format(@"{0}setting\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, fileName);
            if (!File.Exists(settingPath))
            {
                MessageBox.Show("配置文件不存在,请先配置");
                return;
            }
            FileStream fs = new FileStream(settingPath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            if (fileName.Equals("database"))
            {
                foreach (var item in connectList)
                {
                    sw.WriteLine(string.Format("{0}|{1}|{2}|{3}|{4}", item.ID, item.IsOpen, item.IP, item.LoginName, item.PassWord));
                }
            }
            else if (fileName.Equals("SelectSQL"))
            {
                foreach (var item in sqlList)
                {
                    sw.WriteLine(string.Format("{0}|{1}|{2}", item.ID, item.SelectSQL, item.SQLName));
                }
            }
            else if (fileName.Equals("savePath"))
            {
                sw.WriteLine(string.Format("1|{0}", createFileSavePath));
                sw.WriteLine(string.Format("2|{0}", bcSoftPath));
            }
            sw.Flush();
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 获取所有连接地址
        /// </summary>
        /// <returns></returns>
        public List<DataBaseConnectModel> GetAll()
        {
            return connectList;
        }

        /// <summary>
        /// 获取指定ID的连接地址信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataBaseConnectModel GetModelIP(int id)
        {
            return connectList.Find(o => o.ID == id);
        }

        /// <summary>
        /// 获取启用的地址信息
        /// </summary>
        /// <returns></returns>
        public DataBaseConnectModel GetOpenModel()
        {
            return connectList.Find(o => o.IsOpen);
        }

        /// <summary>
        /// 获取指定ID的查询语句
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SelectSQLModel GetModelSelectSQL(string id)
        {
            return sqlList.Find(o => o.ID == id);
        }

        /// <summary>
        /// 修改TXT文件
        /// </summary>
        /// <param name="model"></param>
        public void Update(DataBaseConnectModel model)
        {
            if (connectList.Exists(o => o.ID == model.ID))
            {
                for (int i = 0; i < connectList.Count; i++)
                {
                    if (connectList[i].ID == model.ID)
                    {
                        connectList[i] = model;
                        WriteTxt("database");
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 保存到TXT文件
        /// </summary>
        /// <param name="model"></param>
        public void Save(DataBaseConnectModel model)
        {
            connectList.Add(model);
            WriteTxt("database");
        }

        /// <summary>
        /// 删除连接地址
        /// </summary>
        /// <param name="model"></param>
        public void Delete(DataBaseConnectModel model)
        {
            if (connectList.Exists(o => o.ID == model.ID))
            {
                connectList.Remove(model);
                WriteTxt("database");
            }
        }

        /// <summary>
        /// 获取最大ID
        /// </summary>
        /// <returns></returns>
        public int GetMaxID()
        {
            int result = 0;
            if (connectList.Count > 0)
            {
                result = connectList.Max(o => o.ID);
            }
            return result;
        }

        /// <summary>
        /// 获取启用的地址ID
        /// </summary>
        /// <returns></returns>
        public int GetOpenID()
        {
            int openId = 0;
            if (connectList.Exists(o => o.IsOpen))
            {
                openId = connectList.Find(o => o.IsOpen).ID;
            }
            return openId;
        }

        /// <summary>
        /// 修改启用地址状态
        /// </summary>
        public void UpdateOpenState()
        {
            connectList.ForEach(o => o.IsOpen = false);
        }

        /// <summary>
        /// 获取数据库表信息集合
        /// </summary>
        /// <returns></returns>
        public List<string> GetDataTable()
        {
            return dtSource;
        }

        /// <summary>
        /// 获取所有查询语句信息
        /// </summary>
        /// <returns></returns>
        public List<SelectSQLModel> GetSelectSql()
        {
            return sqlList;
        }

        /// <summary>
        /// 添加查询语句
        /// </summary>
        /// <param name="sqlModel"></param>
        public void AddSelectSQL(SelectSQLModel sqlModel)
        {
            sqlList.Add(sqlModel);
            WriteTxt("SelectSQL");
        }

        /// <summary>
        /// 修改查询语句
        /// </summary>
        /// <param name="sqlModel"></param>
        public void UpdateSelectSQL(SelectSQLModel sqlModel)
        {
            for (int i = 0; i < sqlList.Count; i++)
            {
                if (sqlList[i].ID == sqlModel.ID)
                {
                    sqlList[i] = sqlModel;
                    WriteTxt("SelectSQL");
                    break;
                }
            }
        }

        /// <summary>
        /// 删除查询语句
        /// </summary>
        /// <param name="_id"></param>
        public void DeleteSelectSQL(string _id)
        {
            for (int i = 0; i < sqlList.Count; i++)
            {
                if (sqlList[i].ID.Equals(_id))
                {
                    sqlList.RemoveAt(i);
                    WriteTxt("SelectSQL");
                    break;
                }
            }
        }

        /// <summary>
        /// 新增/修改的标识是否已经存在
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public bool IsExistsID(string _id)
        {
            return sqlList.Exists(o => o.ID == _id);
        }

        /// <summary>
        /// 修改生成文件保存地址
        /// </summary>
        /// <param name="path"></param>
        public void UpdateSaveCreateFilePath(string path)
        {
            this.createFileSavePath = path;
            WriteTxt("savePath");
        }

        /// <summary>
        /// 修改对比软件路径
        /// </summary>
        /// <param name="path"></param>
        public void UpdateSaveBCSoftPath(string path)
        {
            this.bcSoftPath = path;
            WriteTxt("savePath");
        }

        /// <summary>
        /// 获取生成文件保存地址
        /// </summary>
        /// <returns></returns>
        public string GetSavePath(int type)
        {
            string result = string.Empty;
            switch (type)
            {
                case 1: result = createFileSavePath; break;
                case 2: result = bcSoftPath; break;
            }
            return result;
        }
    }
}
